package FrameWork.World;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
public class GodManager {

    private Logger logger = Logger.getLogger(GodManager.class);
    private God[] gods;
    private AtomicInteger counter = new AtomicInteger(0);
    private GodFactory godFactory = new GodFactory();

    public GodManager(){
        int availProcessors = Runtime.getRuntime().availableProcessors();
        gods = new God[availProcessors*2+1];
        for (int i=0;i<gods.length;i++){
            gods[i] = godFactory.newGod();
            gods[i].start();
        }
    }

    //负载均衡地分配场景给各个天神
    public void deployScene(AbstractScene scene){
        while (true){
            int idx = counter.getAndIncrement()%gods.length;
            God god = gods[idx];
            if (!god.isAlive()){
                reviveGod(idx);
                continue;
            }
            god.registerScene(scene);
            break;
        }
    }

    //复活天神
    private void reviveGod(int idx){
        if (gods.length<=idx){
            return;
        }
        God god = gods[idx];
        if (!god.isAlive()){
            gods[idx] = godFactory.newGod();
        }
    }

}
